from time import sleep

from config import constants
from lib.adb_ import kill, start, click_by_image, init_screenshot_path, is_exsit
from lib.decorators import count_exec_time
from obj import obj_info
from submodules.common.lib.datetime_ import get_timestamp_unix
from submodules.common.lib.log_ import get_logger

logger = get_logger()


@count_exec_time
def 登录账号(timeout=60 * 5):
    timestamp_start = get_timestamp_unix()

    while True:
        click_by_image(obj_info.主页面__邀请组队弹窗__取消按钮)
        init_screenshot_path()
        time_spent = int(get_timestamp_unix()) - int(timestamp_start)
        if time_spent > timeout:
            break

        click_by_image(obj_info.主页面__托管弹窗__进入游戏按钮)
        click_by_image(obj_info.登录页面__默认__进入游戏按钮)
        sleep(3)

        click_by_image(obj_info.区组选择页__默认页面2__已有角色选项)
        click_by_image(obj_info.区组选择页__默认页面__默认区组, obj_info.区组选择页__默认页面__区组标题)
        sleep(3)
        click_by_image(obj_info.区组选择页__默认页面__默认人物, obj_info.区组选择页__默认页面__区组标题)

        click_by_image(obj_info.区组选择页__登录确认弹窗__确认按钮)
        click_by_image(obj_info.区组选择页__登录确认弹窗2__确认按钮)

        res = is_exsit(obj_info.主页面__默认__人物头像区域)
        if res:
            return True
            # sleep(1)  # 等待0.5秒不够使用~~
        #     if is_exsit(obj_info.主页面__人物信息弹窗_水系账号__编号区域):
        #         res2 = "水系账号"
        #         logger.info(f"当前账号类型:{res2}")
        #         for i in range(3):
        #             res = click_by_image(obj_info.主页面__人物信息弹窗__关闭按钮)
        #             if res:
        #                 break
        #         return res2
        #     if is_exsit(obj_info.主页面__人物信息弹窗_木系账号__编号区域):
        #         res2 = "木系账号"
        #         logger.info(f"当前账号类型:{res2}")
        #         for i in range(3):
        #             res = click_by_image(obj_info.主页面__人物信息弹窗__关闭按钮)
        #             if res:
        #                 break
        #         return res2
        #     if is_exsit(obj_info.主页面__人物信息弹窗_火系账号__编号区域):
        #         res2 = "火系账号"
        #         logger.info(f"当前账号类型:{res2}")
        #         for i in range(3):
        #             res = click_by_image(obj_info.主页面__人物信息弹窗__关闭按钮)
        #             if res:
        #                 break
        #         return res2
        # click_by_image(obj_info.主页面__人物信息弹窗__关闭按钮)


@count_exec_time
def 启动APP并登录账号(try_times=3):
    logger.info("启动APP并登录账号")
    for i in range(try_times):
        kill(constants.PACKAGE_NAME_WENDAO)
        sleep(3)
        start(constants.PACKAGE_NAME_WENDAO, constants.ACTIVITY_NAME_WENDAO_MAIN)
        sleep(15)

        res = 登录账号()
        if res is not None:
            return res


if __name__ == "__main__":

    def __test_启动APP并登录账号():
        res = 启动APP并登录账号()
        print(res)

    __test_启动APP并登录账号()
